<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>设备信息管理</title>
</head>
<body>
<h1>设备信息管理</h1>

<h2>设备列表</h2>
<button onclick="loadEquipmentList()">查询</button>
<button onclick="saveEquipmentList()">保存</button>

<!-- 新增基础URL配置区域，方便修改 -->
<div style="margin: 10px 0;">
    <label>接口基础URL: </label>
    <input type="text" id="baseUrl" value="http://localhost:8080" style="width: 300px;">
    <small>（根据你的后端服务地址修改）</small>
</div>

<table border="1" style="margin-top: 10px;">
    <thead>
    <tr>
        <th>ID</th>
        <th>名称</th>
        <th>描述</th>
    </tr>
    </thead>
    <tbody id="equipmentTableBody">
    <!-- 设备数据将在这里显示 -->
    </tbody>
</table>

<div id="message" style="margin-top: 10px; color: blue;"></div>

<script>
    let equipmentList = [];

    // 获取基础URL
    function getBaseUrl() {
        return document.getElementById("baseUrl").value.trim();
    }

    // 加载设备列表
    function loadEquipmentList() {
        setMessage("加载中...");
        const baseUrl = getBaseUrl();
        const url = `${baseUrl}/base/equipment/v1/list`;

        fetch(url)
            .then(response => {
                if (!response.ok) {
                    if (response.status === 404) {
                        throw new Error(`404 未找到接口: ${url}，请检查地址是否正确`);
                    } else if (response.status === 500) {
                        throw new Error("500 服务器内部错误，请检查后端服务是否启动");
                    } else {
                        throw new Error(`加载失败: 状态码 ${response.status}`);
                    }
                }
                return response.json();
            })
            .then(data => {
                equipmentList = data;
                renderTable();
                setMessage("加载成功，共 " + data.length + " 条数据");
            })
            .catch(error => {
                setMessage("错误: " + error.message, "red");
            });
    }

    // 保存设备列表
    function saveEquipmentList() {
        if (equipmentList.length === 0) {
            setMessage("没有数据可保存", "red");
            return;
        }

        setMessage("保存中...");
        const baseUrl = getBaseUrl();
        const url = `${baseUrl}/base/equipment/v1/save`;

        fetch(url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(equipmentList)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`保存失败: 状态码 ${response.status}`);
            }
            return response.json();
        })
        .then(success => {
            if (success) {
                setMessage("保存成功");
            } else {
                setMessage("保存失败", "red");
            }
        })
        .catch(error => {
            setMessage("错误: " + error.message, "red");
        });
    }

    // 渲染表格数据
    function renderTable() {
        const tableBody = document.getElementById("equipmentTableBody");
        tableBody.innerHTML = "";

        equipmentList.forEach(equipment => {
            const row = document.createElement("tr");

            // ID单元格（可编辑）
            const idCell = document.createElement("td");
            const idInput = document.createElement("input");
            idInput.value = equipment.id || "";
            idInput.onchange = (e) => {
                equipment.id = e.target.value;
            };
            idCell.appendChild(idInput);

            // 名称单元格（可编辑）
            const nameCell = document.createElement("td");
            const nameInput = document.createElement("input");
            nameInput.value = equipment.name || "";
            nameInput.onchange = (e) => {
                equipment.name = e.target.value;
            };
            nameCell.appendChild(nameInput);

            // 描述单元格（可编辑）
            const descCell = document.createElement("td");
            const descInput = document.createElement("input");
            descInput.value = equipment.desc || "";
            descInput.onchange = (e) => {
                equipment.desc = e.target.value;
            };
            descCell.appendChild(descInput);

            row.appendChild(idCell);
            row.appendChild(nameCell);
            row.appendChild(descCell);
            tableBody.appendChild(row);
        });

        // 添加一行空数据用于新增
        addEmptyRow();
    }

    // 添加空行用于新增设备
    function addEmptyRow() {
        const tableBody = document.getElementById("equipmentTableBody");
        const row = document.createElement("tr");

        const idCell = document.createElement("td");
        const idInput = document.createElement("input");
        idInput.placeholder = "新ID";

        const nameCell = document.createElement("td");
        const nameInput = document.createElement("input");
        nameInput.placeholder = "新名称";

        const descCell = document.createElement("td");
        const descInput = document.createElement("input");
        descInput.placeholder = "新描述";

        const addCell = document.createElement("td");
        const addButton = document.createElement("button");
        addButton.textContent = "添加";
        addButton.onclick = () => {
            const newEquipment = {
                id: idInput.value,
                name: nameInput.value,
                desc: descInput.value
            };
            equipmentList.push(newEquipment);
            renderTable();
        };

        idCell.appendChild(idInput);
        nameCell.appendChild(nameInput);
        descCell.appendChild(descInput);
        addCell.appendChild(addButton);

        row.appendChild(idCell);
        row.appendChild(nameCell);
        row.appendChild(descCell);
        row.appendChild(addCell);

        tableBody.appendChild(row);
    }

    // 显示消息
    function setMessage(text, color = "blue") {
        const messageElement = document.getElementById("message");
        messageElement.textContent = text;
        messageElement.style.color = color;
    }
</script>
</body>
</html>